<!--商品列表，推荐商品，首页商品展示-->
<script setup lang="ts">
import useOrder from '~/composables/useOrder'
import { useUserStore } from '~/stores/user'
const userStore = useUserStore()
// 中文注释：新增 onGetCartCount 用于加入购物车后同步购物车数量
const { handlerProDetailLink, onGetCartCount } = useOrder()
import { toRefs, computed, ref } from 'vue'
import { collectAddApi, collectCancelApi, cartAddApi, productDetailApi } from '~/server/goodsApi'
import feedback from '~/utils/feedback'
const props = defineProps({
  //列表数据
  item: {
    type: Object,
    default: null,
  },
  //图片大小
  sizeData: {
    type: Object,
    default: {
      width: '228px',
      height: '228px',
    },
  },
})
const { item, sizeData } = toRefs(props)

// 中文注释：服务端返回的收藏列表项为 { productId: number, ... }，因此需用 productId 对比
const isCollect = computed(() => {
  return userStore.collections ? userStore.collections.some((col: any) => col.productId === props.item.id) : false
})

/**
 * 地址跳转
 */
const handlerNuxtLink = async (id: number) => {
  await handlerProDetailLink(id, 0)
}

/**
 * 选品/取消选品（悬浮面板点击）
 */
const isHandling = ref(false)
const handleCollect = async (e?: Event) => {
  // 中文注释：阻止冒泡，避免触发整卡片的跳转
  e?.stopPropagation?.()
  if (!userStore.isLogin) {
    // 调起登录
    // nuxtApp.$onHandlerLogin()
    feedback.msgWarning('请先登录')
    return
  }
  if (isHandling.value) return
  isHandling.value = true
  try {
    const productId = props.item.id
    if (isCollect.value) {
      await collectCancelApi({ ids: productId })
      // 同步本地 collections
      const next = (userStore.collections || []).filter((x: any) => x.productId !== productId)
      userStore.setCollections(next)
      feedback.msgSuccess('取消成功')
    } else {
      await collectAddApi({ productId, category: 0 })
      // 同步本地 collections
      const next = [ ...((userStore.collections as any[]) || []), { productId } ]
      userStore.setCollections(next)
      feedback.msgSuccess('选品成功')
    }
  } finally {
    isHandling.value = false
  }
}

/**
 * 中文注释：加入购物车（悬浮面板点击）
 * 列表卡片不涉及规格与数量选择，默认数量为 1，规格唯一值传 0（无规格）
 */
const isAddingCart = ref(false)
// 中文注释：从商品规格值中挑选一个可用的规格（优先默认且有库存，其次任一有库存）
const pickValidSkuId = (productValueObj: Record<string, any>) => {
  const values = Object.values(productValueObj || {})
  if (!values.length) return 0
  // 优先默认规格且库存>0
  const def = values.find((v: any) => v.isDefault && v.stock > 0)
  if (def) return def.id || 0
  // 其次任一库存>0
  const anyStock = values.find((v: any) => v.stock > 0)
  return (anyStock && anyStock.id) || 0
}
const handleAddCart = async (e?: Event) => {
  // 中文注释：阻止冒泡，避免触发整卡片跳转
  e?.stopPropagation?.()
  if (!userStore.isLogin) {
    feedback.msgWarning('请先登录')
    return
  }
  // 库存校验（无库存不允许加购）
  if (props.item?.stock === 0) {
    feedback.msgWarning('库存不足，无法加入购物车')
    return
  }
  if (isAddingCart.value) return
  isAddingCart.value = true
  try {
    // 中文注释：加入购物车前查询商品详情，获取规格并选择一个可用规格
    const detailParams = { id: props.item.id, marketingType: 0, type: 0 }
    const detail = await productDetailApi(detailParams as any)
    let productAttrUnique = 0
    if (detail && detail.productAttr && detail.productAttr.length && detail.productValue) {
      productAttrUnique = pickValidSkuId(detail.productValue)
      if (!productAttrUnique) {
        // 无可用规格（可能都无库存），提示前往详情页选择
        feedback.msgWarning('该商品规格暂无可用库存，请前往详情页选择')
        return
      }
    }
    const payload = {
      productId: props.item.id,
      cartNum: 1,
      productAttrUnique, // 若无规格则为 0，有规格则为可用规格 ID
    }
    await cartAddApi(payload)
    feedback.msgSuccess('添加购物车成功')
    // 更新购物车数量
    onGetCartCount && onGetCartCount()
  } catch (err) {
    // 已在全局拦截器/feedback 处理错误提示
  } finally {
    isAddingCart.value = false
  }
}

// 计算利润率
const profitRate = (item: any) => {
  return ((item.price - item.cost) / item.cost * 100).toFixed(2)
}
</script>

<template>
  <div class="productItem cursors">
    <div data-aos-anchor-placement="top-bottom" @click="handlerNuxtLink(item.id)">
      <div class="borRadius bg-#FFFFFF relative" :style="{ width: sizeData.width }">
        <!-- <div class="relative"> -->
          <div v-show="item.stock===0" class="sellOut">已售罄</div>
          <!-- 中文注释：以下为“原始写法”，保留为注释，方便随时恢复 -->
          
          <el-image
            class="backImg"
            :src="item.image"
            :style="{ width: sizeData.width, height: sizeData.height }"
          ></el-image>
         
          <!-- 中文注释：新写法——使用原生 img，并设置 referrerpolicy 以避免 Referer 导致的防盗链（返回 403） -->
          <!-- <img
            class="backImg"
            :src="item.image"
            :style="{ width: sizeData.width, height: sizeData.height }"
            referrerpolicy="no-referrer"
            alt=""
          /> -->
          <div
            v-if="item.activityStyle"
            :style="{ backgroundImage: `url(${item.activityStyle})` }"
            class="border-picture backImg"
          ></div>
          <!-- 悬浮上滑内容区域：按钮左右结构，统一使用选品的背景色 -->
          <div class="hover-slide">
            <div class="hover-slide__row">
              <div class="hover-slide__btn" @click.stop="handleCollect">
                <span
                  class="iconfont mr-6px"
                  :class="!isCollect ? 'text-white icon-baobeishoucang' : 'text-yellow-50 icon-yishoucang'"
                ></span>
                <span
                  class="hover-slide__text"
                  :class="!isCollect ? 'text-white' : 'text-yellow-50'"
                >{{ isCollect ? '取消选品' : '选品' }}</span>
              </div>
              <div class="hover-slide__btn" @click.stop="handleAddCart">
                <span class="iconfont icon-gouwuche mr-6px"></span>
                <span class="hover-slide__text">加入购物车</span>
              </div>
            </div>
          </div>
        <!-- </div> -->
        <div
          class="bg-white px12px py-14px content h-177px flex flex-justify-between"
          style="margin-top: -5px; flex-direction: column"
        >
          <div class="line2 text-14px fontColor333 products-name h-36px lh-19px acea-row">
            <div
              v-if="item.productTags && item.productTags.locationLeftTitle.length"
              class="inline-block text-12px bg-color text-#fff b-rd-2px py-2px mr-6px px-4px line-heightOne"
            >
              {{ item.productTags.locationLeftTitle[0].tagName }}
            </div>
            {{ item.name }}
          </div>
          <div v-if="item.productTags && item.productTags.locationUnderTitle.length" class="acea-row">
            <div
              v-for="items in item.productTags.locationUnderTitle.length > 3
                ? item.productTags.locationUnderTitle.slice(0, 3)
                : item.productTags.locationUnderTitle"
              :key="items.id"
              class="text-12px line-heightOne font-color base-border b-color-#E93323 b-rd-2px px4px py2px mr8px productTags"
            >
              {{ items.tagName }}
            </div>
          </div>
          <svip-price :productPrice="item" :priceStyle="{ fontSize: '20px' }"></svip-price>
          <div class="w-full mt-5px">
            <div class="text-12px text-#999 flex items-center justify-between">
              <div>利润率：</div>
              <div class="text-red-500">{{ profitRate(item) }}%</div>
            </div>
            <div class="text-12px text-#999 flex items-center justify-between my-2px">
              <div>零售价：</div>
              <div>￥{{ item.price }}</div>
            </div>
            <div class="text-12px text-#999 flex items-center justify-between">
              <div>最低控价：</div>
              <div>￥{{ item.otPrice }}</div>
            </div>
          </div>
          <!-- <div class="text-12px text-#999 line-heightOne">已售{{ item.sales }}{{ item.unitName }}</div> -->
          <!-- <div v-if="item.merName" class="mt-15px">
            <span class="iconfont icon-guanzhudianpu mr-5px font-color"></span>
            <span class="text-12px text-#666">{{ item.merName }}</span>
          </div> -->
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.backImg {
  border-top-left-radius: 16px;
  border-top-right-radius: 16px;
}
.content {
  border-bottom-left-radius: 16px;
  border-bottom-right-radius: 16px;
}
/* 悬浮上滑面板样式 */
.productItem {
  position: relative;
}
.relative {
  position: relative;
  overflow: hidden;
}
.hover-slide {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  /* 中文注释：单行高度，回归更小的初始下移 */
  transform: translateY(110%);
  transition: transform 0.25s ease;
  pointer-events: none; /* 不影响原有点击行为（进入详情） */
}
.hover-slide__row {
  display: flex;
  pointer-events: all; /* 允许内部内容可点击 */
}
.hover-slide__btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 46px;
  background: #e93323; /* 与选品按钮相同背景色 */
  color: #fff;
  cursor: pointer;
}
.hover-slide__btn + .hover-slide__btn {
  /* 中文注释：左右按钮之间的分隔线 */
  border-left: 1px solid rgba(255, 255, 255, 0.2);
}
.hover-slide__text {
  font-size: 14px;
}
.productItem:hover .hover-slide {
  transform: translateY(0);
}
</style>
